package com.bruce.starts.demo.thread.demo;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class TeaDemo2 {
    public static void main(String[] args) {
        TeaDemo2 teaDemo2 = new TeaDemo2();
        //teaDemo2.makeTea();
        teaDemo2.test();
    }

    public void test(){
        CompletableFuture<String> f1 =
                CompletableFuture.supplyAsync(()->{
                    int t = RandomUtil.randomInt(0,10);
                    System.out.println("f1:随机数"+t);
                    sleep(t, TimeUnit.SECONDS);
                    return String.valueOf(t);
                });

        CompletableFuture<String> f2 =
                CompletableFuture.supplyAsync(()->{
                    int t = RandomUtil.randomInt(0,10);
                    System.out.println("f2:随机数"+t);
                    sleep(t, TimeUnit.SECONDS);
                    return String.valueOf(t);
                });

        CompletableFuture<String> f3 =
                f1.applyToEither(f2,s -> s+1);

        System.out.println(f3.join());
    }

    public void makeTea(){
        CompletableFuture<Void> f1 = CompletableFuture.runAsync(()->{
            System.out.println("T1:洗水浒...");
            sleep(1,TimeUnit.SECONDS);
            System.out.println("T1: 烧开水...");
            sleep(15, TimeUnit.SECONDS);
        });
        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(()->{
            System.out.println("T2: 洗茶壶...");
            sleep(1, TimeUnit.SECONDS);

            System.out.println("T2: 洗茶杯...");
            sleep(2, TimeUnit.SECONDS);

            System.out.println("T2: 拿茶叶...");
            sleep(1, TimeUnit.SECONDS);
            return " 龙井 ";
        });

        CompletableFuture<String> f3 = f1.thenCombine(f2,(vo,tf)->{
            System.out.println("T1: 拿到茶叶:" + tf);
            System.out.println("T1: 泡茶...");
            return " 上茶:" + tf;
        });

        // 等待任务 3 执行结果
        System.out.println(f3.join());
    }

    public void sleep(int time , TimeUnit unit){
        try {
            unit.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
